const webpack = require('webpack');
const HtmlwebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin')
const nodeExternals = require('webpack-node-externals')
const {
    VueLoaderPlugin
} = require('vue-loader')
var path = require('path');

let _rootpath = ''

if (process.platform === 'win32') {
    _rootpath = __dirname.substr(0, __dirname.lastIndexOf('\\'))
} else {
    _rootpath = __dirname.substr(0, __dirname.lastIndexOf('/'))
}

let dev = process.argv;

const fs = require('fs');
let _package = fs.readFileSync(_rootpath + '/package.json', 'utf-8');
_package = JSON.parse(_package);
if (dev.indexOf('development') === -1) {
    let _point = false;
    let _version = _package.version;
    _version = _version.split('-');
    if (_version.length < 2) {
        _version = _version[0].split('.');
        _point = true;
    }
    _version[_version.length - 1] = parseInt(_version[_version.length - 1]) + 1;
    _version[_version.length - 1] = _version[_version.length - 1].toString();

    let _newversion = "";
    if (_point) {
        for (let i = 0; i < _version.length; i++) {
            _newversion += _version[i] + '.';
        }
    } else {
        for (let i = 0; i < _version.length; i++) {
            _newversion += _version[i] + '-';
        }
    }
    _newversion = _newversion.substring(0, _newversion.length - 1);

    _package.version = _newversion;
}
fs.writeFileSync(_rootpath + '/package.json', JSON.stringify(_package, null, 4));
let _npackage = {};
_npackage.name = _package.name;
_npackage.version = _package.version;
_npackage.description = _package.description;
_npackage.main = _package.main;
_npackage.repository = _package.repository;
_npackage.keywords = _package.keywords;
_npackage.author = _package.author;
_npackage.license = _package.license;
_npackage.dependencies = {};
fs.writeFileSync(_rootpath + '/build/package.json', JSON.stringify(_npackage, null, 4));


//服务入口
var server = {
    target: 'node',
    context: _rootpath,
    // 入口
    entry: './src/server/server.ts',
    // 输出的文件名
    output: {
        path: path.resolve(_rootpath, 'build'),
        filename: 'server.js'
    },
    stats: "errors-only",
    plugins: [
        new CleanWebpackPlugin({
            dry: false,
            cleanOnceBeforeBuildPatterns: ['**/*', '!package.json', '!build.md'],
            root: _rootpath,
            verbose: true,
            exclude: ['package.json', 'build.md']
        }),
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.BannerPlugin({
            banner: 'zifeng911@163.com'
        })
    ],
    module: {
        rules: [
            // all files with a `.ts` extension will be handled by `ts-loader`
            {
                test: /\.ts$/,
                //use: 'ts-loader',
                use: [{
                    loader: 'ts-loader',
                }]
            }, {
                test: /\.ts$/,
                use: {
                    loader: 'tslint-loader',
                    options: {
                        configFile: _rootpath + '/.config/tslint.json'
                    }
                },
                exclude: /node_modules/
            },
        ]
    },
    resolve: {
        extensions: ['.js', '.json', '.ts'], //后缀名自动补全
        alias: {}
    },
    node: {
        __filename: false,
        __dirname: false,
        setImmediate: false
    },
    externals: [nodeExternals()]
}

var www = {
    target: 'node',
    // 入口
    entry: './src/www/main.ts',
    // 输出的文件名
    output: {
        path: path.resolve(_rootpath, 'build/www'),
        filename: 'renderer-[hash].js'
    },
    stats: "errors-only",
    plugins: [
        new VueLoaderPlugin(),
        new HtmlwebpackPlugin({
            title: 'Home',
            filename: 'index.html',
            template: './src/www/main.html'
        }),
        new ForkTsCheckerWebpackPlugin({
            tslint: _rootpath + '/.config/tslint.json',
            vue: true
        }),
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.BannerPlugin({
            banner: 'zifeng911@163.com'
        }),
        new CopyWebpackPlugin([{
            from: _rootpath + '/src/www/error.html',
            to: _rootpath + '/build/www/error.html',
            toType: 'file'
        }])
    ],
    module: {
        rules: [
            // all files with a `.ts` extension will be handled by `ts-loader`
            {
                test: /\.vue$/,
                use: {
                    loader: 'vue-loader',
                    options: {
                        optimizeSSR: false
                    }
                }
            }, {
                test: /\.pug$/,
                oneOf: [
                    // 这条规则应用到 Vue 组件内的 `<template lang="pug">`
                    {
                        resourceQuery: /^\?vue/,
                        use: ['pug-plain-loader']
                    },
                    // 这条规则应用到 JavaScript 内的 pug 导入
                    {
                        use: ['raw-loader', 'pug-plain-loader']
                    }
                ]
            },
            {
                test: /\.ts$/,
                use: {
                    loader: 'ts-loader',
                    options: {
                        appendTsSuffixTo: [/\.vue$/],
                        transpileOnly: true
                        // exclude: /node_modules/,
                    }
                }
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader'
            },
            {
                test: /\.scss$/,
                loader: ['style-loader', 'css-loader', 'fast-sass-loader']
            }, {
                test: /\.(eot|ttf|woff|woff2)(\?\S*)?$/,
                loader: 'file-loader',
                options: {
                    name: 'assets/fonts/[name]-[hash].[ext]'
                }
            }
            , {
                test: /\.(png|jpe?g|gif|svg|ico)(\?\S*)?$/,
                loader: 'file-loader',
                options: {
                    name: 'assets/images/[name]-[hash].[ext]'
                }
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx', '.ts', '.vue', '.css', '.json'], //后缀名自动补全
        alias: {
            vue$: 'vue/dist/vue.esm.js',
            router: 'vue-router/dist/vue-router.js'
        },
        modules: [
            path.resolve(_rootpath, 'node_modules'),
            path.resolve(_rootpath, 'i18n')
        ]
    }
}

module.exports = [server, www];